import GlobelConst from "@/config/GlobelConst.js";
import {ElLoading} from 'element-plus';

export async function get(url) {
    return request(url, null, "GET");

}

export async function post(url, param) {

    return request(url, param, "POST");
}

export function getBaseUrl() {
    var baseUrl = GlobelConst.baseUrl;
    return baseUrl;
}

async function request(url, param, method) {
    var baseUrl = GlobelConst.baseUrl;

    var elLoadingComponent = ElLoading.service({
        lock: true, text: '加载中', spinner: 'el-icon-loading', background: 'rgb(85 0 0 / 0%)'
    });

    var s = {
        method: method, headers: {
            "Content-Type": "application/json"
        }, body: JSON.stringify(param || {}), mode: 'cors'
    };
    if (method == "GET") {
        s.body = null;
    }
    let data=null;
  try {
       data = await fetch(`http://${baseUrl}${url}`, s).then(function (response) {
          elLoadingComponent.close();
          //response.status表示响应的http状态码
          if (response.status === 200) {
              //json是返回的response提供的一个方法,会把返回的json字符串反序列化成对象,也被包装成一个Promise了
              return response.json();
          } else {
              return {}
          }
      });
  }catch (ex){
        console.error(ex)
  }
    return data?.data;
}

export async function getStream(url) {
    return requestStream(url, null, "GET");

}

async function requestStream(url, param, method) {
    var baseUrl = GlobelConst.baseUrl;

    var elLoadingComponent = ElLoading.service({
        lock: true, text: '加载中', spinner: 'el-icon-loading', background: 'rgb(85 0 0 / 0%)'
    });

    var s = {
        method: method, headers: {
            "Content-Type": "application/json"
        }, body: JSON.stringify(param || {}), mode: 'cors'
    };
    if (method == "GET") {
        s.body = null;
    }
    const data = await fetch(`http://${baseUrl}${url}`, s).then(function (response) {
        elLoadingComponent.close();
        //response.status表示响应的http状态码
        if (response.status === 200) {
            //json是返回的response提供的一个方法,会把返回的json字符串反序列化成对象,也被包装成一个Promise了
            return response.blob();
        } else {
            return {}
        }
    });
    return data;
}